<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Str;

class FilterParameters
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $filteredParams = [];
        foreach ($request->all() as $key => $value) {
            $filteredParams[$key] = $this->filter($key, $value);
        }
        $request->replace($filteredParams);
        return $next($request);
    }

    /**
     * filter params
     * @param int $key
     * @param $value
     * @return mixed $filteredValue
     */
    private function filter($key, $value)
    {
        // 没传参数其值为null，则不处理仍然返回null
        if (is_null($value)) {
            return $value;
        }

        if (Str::contains($key, [
            'id',
            'quantity',
            'bookId',
            'chapter_id',
            'orderBy',
            'isOver',
            'lastReadChapter',
            'index',
        ])) {
            return (int)$value;
        }

        if (Str::contains($key, 'price')) {
            return (float)$value;
        }

        return $value;
    }
}
